package chess;

import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.preferences.IPreferencesService;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;

import chess.database.DBConnection;
import chess.database.JavaDBConnection;
import chess.model.ConnectionDetails;
import chess.model.Session;

/**
 * This class controls all aspects of the application's execution
 */
public class Application implements IApplication {
	
//	private String database = "";
	public static final String PLUGIN_ID = "chess";
	
	
	public Object start(IApplicationContext context) throws Exception {
		Display display = PlatformUI.createDisplay();
//		DBConnection db = new JavaDBConnection();
		setDatabase();
		try {
			final Session session = Session.getInstance();
			if (!login(session))
				return IApplication.EXIT_OK;
			int returnCode = PlatformUI.createAndRunWorkbench(display,
					new ApplicationWorkbenchAdvisor());
			if (returnCode == PlatformUI.RETURN_RESTART)
				return IApplication.EXIT_RESTART;
			return IApplication.EXIT_OK;
		} finally {
			display.dispose();
		}

	}

	public void stop() {
		final IWorkbench workbench = PlatformUI.getWorkbench();
		if (workbench == null)
			return;
		final Display display = workbench.getDisplay();
		display.syncExec(new Runnable() {
			public void run() {
				if (!display.isDisposed())
					workbench.close();
			}
		});
	}

//	private boolean login(final Session session) {
//		ConnectionDetails d = new ConnectionDetails("dovecr", "freechess.org",
//				"hovno");
//		ServerConnection con = new ServerConnection(d.getServer(), 5000);
//		con.login(d.getUserId(), d.getPassword());
//		session.setConnection(con);
//		session.setConnectionDetails(d);
//		return true;
//	}
	
	private boolean login(final Session session) {
		boolean firstTry = true;
		LoginDialog loginDialog = new LoginDialog(null);
		System.out.println("1");
		while (session.getConnection() == null
				|| !session.getConnection().isAuthenticated()) {
			System.out.println("2");
			IPreferencesService service = Platform.getPreferencesService();
			boolean auto_login = service.getBoolean(Application.PLUGIN_ID,GeneralPreferencePage.AUTO_LOGIN, true, null);
			ConnectionDetails details = loginDialog.getConnectionDetails();
			if (!auto_login || details == null || !firstTry) {
				if (loginDialog.open() != Window.OK)
					return false;
				details = loginDialog.getConnectionDetails();
			}
			firstTry = false;
			session.setConnectionDetails(details);
//			connectWithProgress(session);
			session.connectAndLogin();
		}
		return true;
	}
	
	private void setDatabase(){
		DBConnection db=JavaDBConnection.getInstance();
		db.connect();
	}
}
